package com.happy_hao.msg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.happy_hao.msg.common.Result;
import com.happy_hao.msg.dto.SenderRequest;
import com.happy_hao.msg.mapper.SenderMapper;
import com.happy_hao.msg.po.Sender;
import com.happy_hao.msg.service.SenderService;
import com.happy_hao.msg.util.SenderUtil;
import com.happy_hao.msg.util.SnowFlakeUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class SenderServiceImpl implements SenderService {

    @Resource
    private SenderMapper senderMapper;

    @Resource
    private SenderUtil senderUtil;

    @Override
    public Result addSender(SenderRequest senderRequest) {
        Sender old = senderUtil.getSender(senderRequest.getUsername());
        if(old != null) {
            return Result.error().message("该邮箱已被添加");
        }
        Sender sender = new Sender();
        sender.setSenderId(SnowFlakeUtil.getSnowFlakeId());
        sender.setHost(senderRequest.getHost());
        sender.setUsername(senderRequest.getUsername());
        sender.setPassword(senderRequest.getPassword());
        Date date = new Date();
        sender.setCreateAt(date);
        sender.setUpdateAt(date);
        senderMapper.insert(sender);
        return Result.success().message("添加邮箱载体成功");
    }

    @Override
    public Result getAllSenders() {
        return Result.success().data("All Senders", senderMapper.selectList(null));
    }

    @Override
    public Result deleteSender(String username) {
        if(senderUtil.getSender(username) == null) {
            return Result.error().message("该邮箱不存在");
        }
        QueryWrapper<Sender> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        senderMapper.delete(queryWrapper);
        return Result.success().message("删除邮箱载体成功");
    }

    @Override
    public Result updateSender(SenderRequest senderRequest) {
        Sender old = senderUtil.getSender(senderRequest.getUsername());
        if(old == null) {
            return Result.error().message("您要修改的邮箱不存在");
        }
        UpdateWrapper<Sender> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("host", senderRequest.getHost());
        updateWrapper.set("password", senderRequest.getPassword());
        updateWrapper.set("update_at", new Date());
        updateWrapper.eq("username", senderRequest.getUsername());
        senderMapper.update(null, updateWrapper);
        return Result.success().message("修改邮箱载体成功");
    }


}
